package com.suneast.suneaststore.modules.homepage;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.util.DiffUtil;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.suneast.suneaststore.R;
import com.suneast.suneaststore.modules.common.Flag;
import com.suneast.suneaststore.modules.homepage.adapter.SubCateListAdapter;
import com.suneast.suneaststore.bean.homepage.FilterBean;
import com.suneast.suneaststore.modules.homepage.event.FilterSetEvent;
import com.suneast.suneaststore.modules.homepage.event.GotSubCate;
import com.suneast.suneaststore.modules.search.FilterItemDiffUtil;
import com.suneast.suneaststore.modules.search.adapter.SearchFilterAdapter;
import com.suneast.suneaststore.modules.search.SearchRequestHandler;
import com.suneast.suneaststore.bean.search.SearchFilterBean;
import com.suneast.suneaststore.bean.search.SearchFilterItemBean;
import com.suneast.suneaststore.modules.search.event.FilterGotEvent;
import com.suneast.suneaststore.modules.search.event.ItemFilterCheckChangeEvent;
import com.suneast.suneaststore.ui.fragments.BaseFragment;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

public class FilterFragment extends BaseFragment implements SubCateListAdapter.OnItemClickListener, BaseQuickAdapter.OnItemChildClickListener {

    private int parentId = 1194;//默认成品id

    public FilterFragment withId(int id) {
        parentId = id;
        return this;
    }

    @Override
    public int setLayout() {
        return R.layout.fragment_filter;
    }

    @OnClick({R.id.btn_reset_filter, R.id.btn_confirm_filter})
    public void onViewClick(View view) {
        switch (view.getId()) {
            case R.id.btn_reset_filter: {
                EventBus.getDefault().post(new FilterSetEvent(true));
                pop();
            }
            break;
            case R.id.btn_confirm_filter: {

                setMinMax();
                EventBus.getDefault().post(new FilterSetEvent(false, price1, price2, filtersList));
                pop();
            }
            break;
        }
    }

    private int price1 = 0;
    private int price2 = 0;

    private void setMinMax() {
        if (price1 > price2) {
            price1 = price1 ^ price2;
            price2 = price1 ^ price2;
            price1 = price1 ^ price2;
        }
    }

    @BindView(R.id.toolbar_filter)
    Toolbar filterToolbar;
    @BindView(R.id.rv_cate)
    RecyclerView cateRV;
    SubCateListAdapter cateAdapter;
    @BindView(R.id.et_min_price)
    EditText minPriceEt;
    @BindView(R.id.et_max_price)
    EditText maxPriceEt;
    @BindView(R.id.layout_no_data_tip)
    LinearLayout noDataTipLayout;
    @BindView(R.id.rv_filter)
    RecyclerView filterRV;
    SearchFilterAdapter filterAdapter;

    @Override
    public void onBindView(@Nullable Bundle savedInstanceState, @NonNull View rootView) {
        EventBus.getDefault().register(this);
        initView();
        HomePageHandler.requestSubCategory(parentId);
    }

    private void initView() {
        filterToolbar.setNavigationOnClickListener((View v) -> pop());

        cateRV.setLayoutManager(new LinearLayoutManager(getContext()));
        filterRV.setLayoutManager(new LinearLayoutManager(getContext()));
        filterAdapter = new SearchFilterAdapter(R.layout.item_search_filter);
        filterAdapter.setOnItemChildClickListener(this);
        filterRV.setAdapter(filterAdapter);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotSubCate(GotSubCate event) {
        if (event.getFlag() == Flag.Result.SUCCEED) {
            List<FilterBean> list = event.getFilterBeanList();
            if (list != null && list.size() > 0) {
                cateAdapter = new SubCateListAdapter(list);
                cateAdapter.setOnItemClickListener(this);
                cateRV.setAdapter(cateAdapter);
                SearchRequestHandler.requestFilters(list.get(0).getId(), "");
            }
        } else {
            Toast.makeText(_mActivity, "获取分类数据失败", Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    public void onItemClick(int id, int pos) {
        cateAdapter.updatePos(pos);
        //请求属性列表
        SearchRequestHandler.requestFilters(id, "");
    }

    private ArrayList<SearchFilterBean> allFilterList;
    private ArrayList<SearchFilterBean> simpleFilterList;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onGotFilters(FilterGotEvent event) {
        Log.e(TAG, "onGotFilters: size = " + event.getFilterBeanList().size());
        if (event.getFilterBeanList().size() > 0) {
            noDataTipLayout.setVisibility(View.GONE);
            allFilterList = event.getFilterBeanList();
            simpleFilterList = getSimpleFilterList(allFilterList);
            ArrayList<SearchFilterBean> adapterList = new ArrayList<>(simpleFilterList);
            filterAdapter.setNewData(adapterList);
        } else {
            noDataTipLayout.setVisibility(View.VISIBLE);
            filterAdapter.setNewData(new ArrayList<>());
        }
    }

    private ArrayList<SearchFilterBean> getSimpleFilterList(ArrayList<SearchFilterBean> sourceList) {
        ArrayList<SearchFilterBean> goalList = new ArrayList<>();
        for (int i = 0, iLength = sourceList.size(); i < iLength; i++) {
            SearchFilterBean sourceBean = sourceList.get(i);
            SearchFilterBean bean = new SearchFilterBean();
            bean.setShowTextAll(sourceBean.isShowTextAll());
            bean.setTitle(sourceBean.getTitle());
            ArrayList<SearchFilterItemBean> itemList = new ArrayList<>();
            for (int j = 0; j < Math.min(3, sourceBean.getItemList().size()); j++) {
                itemList.add(sourceBean.getItemList().get(j));
            }
            bean.setItemList(itemList);
            goalList.add(bean);
        }
        return goalList;
    }

    @Override
    public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
        //替换数据
        ArrayList<SearchFilterBean> oldList = (ArrayList<SearchFilterBean>) adapter.getData();
        ArrayList<SearchFilterBean> newList = new ArrayList<>(oldList);

        if (oldList.get(position).getItemList().size()
                == allFilterList.get(position).getItemList().size()) {
            newList.remove(position);
            SearchFilterBean bean = SearchFilterBean.copy(simpleFilterList.get(position));
            bean.setShowingAll(false);
            newList.add(position, bean);
        } else {
            newList.remove(position);
            SearchFilterBean bean = SearchFilterBean.copy(allFilterList.get(position));
            bean.setShowingAll(true);
            newList.add(position, bean);
        }
        DiffUtil.DiffResult diffResult =
                DiffUtil.calculateDiff(new FilterItemDiffUtil(oldList, newList), true);
        diffResult.dispatchUpdatesTo(filterAdapter);
        filterAdapter.setNewData(newList);
        if (position == adapter.getData().size() - 1) {
            filterRV.scrollBy(0, 10000);
        }
    }

    private ArrayList<String> filtersList = new ArrayList<>();

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onItemFilterCheckChange(ItemFilterCheckChangeEvent event) {
        for (int i = 0, length = allFilterList.size(); i < length; i++) {
            if (allFilterList.get(i).getTitle().equals(event.getTitle())) {
                ArrayList<SearchFilterItemBean> itemList = allFilterList.get(i).getItemList();
                for (int j = 0, jLength = itemList.size(); j < jLength; j++) {
                    if (itemList.get(j).getValue() == event.getBean().getValue()) {
                        itemList.get(j).setCurrent(event.isChecked());
                        break;
                    }
                }
                break;
            }
        }

        for (int i = 0, length = simpleFilterList.size(); i < length; i++) {
            if (simpleFilterList.get(i).getTitle().equals(event.getTitle())) {
                ArrayList<SearchFilterItemBean> itemList = simpleFilterList.get(i).getItemList();
                for (int j = 0, jLength = itemList.size(); j < jLength; j++) {
                    if (itemList.get(j).getValue() == event.getBean().getValue()) {
                        itemList.get(j).setCurrent(event.isChecked());
                        break;
                    }
                }
                break;
            }
        }
        String filterStr = createFilterStr(event.getBean().getValue(), event.getBean().getKey());
        if (event.isChecked()) {
            filtersList.add(filterStr);
        } else {
            filtersList.remove(filterStr);
        }
    }

    private String createFilterStr(int value, int key) {
        return "{\"value\":\"" + value + "\",\"key\":\"" + key + "\"}";
    }
}
